package net.saralab;

import com.mysql.jdbc.StringUtils;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.messaging.PluginMessageListener;
import org.bukkit.scheduler.BukkitRunnable;

public class AntiCheat extends JavaPlugin implements PluginMessageListener, Listener {
	private static List<String> bio = new ArrayList();
	private static LinkedHashMap<String, Ha> joni = new LinkedHashMap();
	private static Map<Player, gao> joda = Collections.synchronizedMap(new HashMap());
	private static int hido;
	private static String maya;
	private static String senya;

	@Override
	public void onEnable() {
		try {
			if (Class.forName("net.saralab.AssWeCan") != null) {
				getLogger().info("AntiCheatMod found! Disabled plugin.");
				getPluginLoader().disablePlugin(this);
				return;
			}
		} catch (ClassNotFoundException localClassNotFoundException) {
			getServer().getPluginManager().registerEvents(this, this);
			Bukkit.getMessenger().registerOutgoingPluginChannel(this, "AntiCheat3");
			Bukkit.getMessenger().registerIncomingPluginChannel(this, "AntiCheat3", this);
			new GG().runTaskTimer(this, 0L, 60L);
			sc();
			dota();
		}
	}

	@Override
	public boolean onCommand(CommandSender shi, Command da, String yo, String[] ne) {
		if (da.getName().equalsIgnoreCase("ac3")) {
			if (!shi.isOp()) {
				shi.sendMessage("§cYou have no permission to do this");
				return true;
			}
			if (ne.length == 1) {
				if ("reload".equalsIgnoreCase(ne[0])) {
					dota();
					shi.sendMessage("§6AntiCheat3 Configuration reloaded");
					return true;
				}
				if ("help".equalsIgnoreCase(ne[0])) {
					shi.sendMessage("§6/ac3 reload§r - §aReload configuration");
					return true;
				}
			}
			shi.sendMessage("§aType §6/ac3 help §afor more infomation");
		}
		return true;
	}

	private void dota() {
		FileConfiguration dora = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "config.yml"));
		maya = dora.getString("Settings.KickedMessage");
		senya = dora.getString("Settings.TimedOutMessage");
		hido = dora.getInt("Settings.MaxWaitTime");
		bio = dora.getStringList("MD5List");
		getLogger().info("Server MD5List:");
		for (String s : bio) {
			getLogger().info(s);
		}
	}

	private void sc() {
		if (new File(getDataFolder(), "config.yml").exists()) {
			return;
		}
		saveDefaultConfig();
	}

	private static String fg(String fg) {
		String big = "";
		try {
			MessageDigest news = MessageDigest.getInstance("MD5");
			news.update(fg.getBytes());
			byte[] too = news.digest();

			StringBuffer simple = new StringBuffer("");
			for (int naive = 0; naive < too.length; naive++) {
				int young = too[naive];
				if (young < 0) {
					young += 256;
				}
				if (young < 16) {
					simple.append("0");
				}
				simple.append(Integer.toHexString(young));
			}
			big = simple.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return big;
	}

	@Override
	public void onPluginMessageReceived(String arg0, Player arg1, byte[] arg2) {
		try {
			String hongkong = new String(arg2, "UTF-8").trim();
			String[] aya = hongkong.split(",");
			hongkong = "";
			for (int i = 0; i < aya.length - 2; i++) {
				hongkong = hongkong + aya[i] + ",";
			}
			if (!StringUtils.isNullOrEmpty(hongkong)) {
				hongkong = hongkong.substring(0, hongkong.length() - 1).replace(" ", "").trim();
			}
			getLogger().info("Client MD5:---" + hongkong);
			boolean isgay = false;
			if (!joni.get(aya[(aya.length - 1)]).excited.equals(aya[(aya.length - 2)])) {
				arg1.kickPlayer(maya);
				return;
			}
			for (int i = 0; i < aya.length - 2; i++) {
				for (int j = 0; j < bio.size(); j++) {
					if (bio.get(j).equalsIgnoreCase(aya[i])) {
						isgay = true;
						break;
					}
					isgay = false;
				}
				if (!isgay) {
					arg1.kickPlayer(maya);
					return;
				}
			}
			joni.get(aya[(aya.length - 1)]).xu = true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	@EventHandler
	public void self(PlayerJoinEvent self) {
		joda.put(self.getPlayer(), new gao(System.currentTimeMillis()));
		new lai(self.getPlayer(), this).runTaskLater(this, 10L);
	}

	private static String excited(int excited) {
		String angry = "abcdef0123456789";
		Random jibenfa = new Random();
		StringBuffer qindian = new StringBuffer();
		for (int i = 0; i < excited; i++) {
			int xuming = jibenfa.nextInt(angry.length());
			qindian.append(angry.charAt(xuming));
		}
		return qindian.toString();
	}

	private void nimena(Player nimena) {
		gao tan = joda.get(nimena);
		if ((joni.get(fg(nimena.getDisplayName())) != null) && (!tan.na)
				&& (tan.dao + hido < System.currentTimeMillis())) {
			if (!joni.get(fg(nimena.getDisplayName())).xu) {
				nimena.kickPlayer(senya);
			}
			tan.na = true;
			joni.remove(fg(nimena.getDisplayName()));
		}
	}

	private class Ha {
		long angry;
		String excited;
		boolean xu;

		Ha(String jizhe, long wukefenggao) {
			this.angry = wukefenggao;
			this.excited = jizhe;
			this.xu = false;
		}
	}

	private class GG extends BukkitRunnable {
		private GG() {
		}

		@Override
		public void run() {
			if (!AntiCheat.joda.isEmpty()) {
				Iterator<Map.Entry<Player, AntiCheat.gao>> tan = AntiCheat.joda.entrySet().iterator();
				while (tan.hasNext()) {
					Map.Entry<Player, AntiCheat.gao> xiao = tan.next();
					Player feng = xiao.getKey();
					AntiCheat.gao sheng = xiao.getValue();
					if (sheng.na) {
						tan.remove();
					} else {
						AntiCheat.this.nimena(feng);
					}
				}
			}
			if (!AntiCheat.joni.isEmpty()) {
				Iterator<Map.Entry<String, AntiCheat.Ha>> bu = AntiCheat.joni.entrySet().iterator();
				while (bu.hasNext()) {
					Map.Entry<String, AntiCheat.Ha> zhi = bu.next();
					AntiCheat.Ha dao = zhi.getValue();
					if (System.currentTimeMillis() - dao.angry > 30000L) {
						bu.remove();
					}
				}
			}
		}
	}

	private class gao {
		long dao;
		boolean na;

		gao(long li) {
			this.dao = li;
			this.na = false;
		}
	}

	private class qu extends BukkitRunnable {
		private Player le;

		private qu(Player hua) {
			this.le = hua;
		}

		@Override
		public void run() {
			if (this.le != null) {
				AntiCheat.this.nimena(this.le);
			}
		}
	}

	private class lai extends BukkitRunnable {
		private Player shi;
		AntiCheat song;

		private lai(Player zu, AntiCheat ying) {
			this.shi = zu;
			this.song = ying;
		}

		@Override
		public void run() {
			try {
				String zici = AntiCheat.excited(32);
				this.shi.sendPluginMessage(this.song, "AntiCheat3",
						new String("," + zici + "," + AntiCheat.fg(this.shi.getDisplayName())).getBytes("UTF-8"));
				AntiCheat.joni.put(AntiCheat.fg(this.shi.getDisplayName()),
						new AntiCheat.Ha(zici, System.currentTimeMillis()));
				new AntiCheat.qu(this.shi).runTaskLater(this.song, AntiCheat.hido / 50 + 1);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
	}
}
